package qs.controls
{
	import flash.geom.Point;
	import flash.display.DisplayObject;
	import mx.core.IUIComponent;
	import mx.core.Application;
	import flash.events.MouseEvent;
	import mx.events.DragEvent;
	import mx.managers.DragManager;

	public class CanvasLayout extends Layout
	{
		private var _mouseTracker : MouseTracker;
		
		[Bindable]
		public var throwEnabled : Boolean = true;
		
		// ILayout interface		
		override public function getMeasuredSize():Point
		{
			return new Point(0, 0);
		}
		
		override public function findItemAt(px:Number, py:Number, seamAligned:Boolean):Number
		{
			// It doesn't make sense to ask for a spot "in between" two items
			// in the canvas layout.
			if (seamAligned)
				return NaN;
			
			// Can't execute this if we aren't attached to a container.
			if (!container)
				return NaN;
			
			// Just do simple hit detection.
			var gPt:Point = container.localToGlobal(new Point(px,py));

			for (var i : int = container.renderers.length-1; i >= 0; i--)
			{
				var r:DisplayObject = container.renderers[i];
				if(r.hitTestPoint(gPt.x,gPt.y,true) == true)
					return i;
			}
			
			return NaN;
		}
		
		override public function generateLayout():void
		{
			// Do nothing here.
		}

		override public function dragStart(e:MouseEvent) : Boolean
		{
			if (throwEnabled)
			{
				_mouseTracker = new MouseTracker();
				_mouseTracker.start();
			}
						
			return false;
		}

		override public function dragOver(e:DragEvent) : Boolean
		{
			if (throwEnabled)
				_mouseTracker.track(container.mouseX, container.mouseY);
			return false;
		}
		
		override public function dragDrop(e:DragEvent) : Boolean
		{
			if (throwEnabled)
				_mouseTracker.end();
			return false;
		}

		override public function dragComplete(e:DragEvent) : Boolean
		{
			if (throwEnabled)
			{
				if (e.action != DragManager.COPY)
				{
					if (_mouseTracker.isThrow())
					{
						var dragFromIndex:Number = Number(e.dragSource.dataForFormat("index"));
		
						var renderer:IUIComponent = container.renderers[dragFromIndex];
						var target:LayoutTarget = animator.targetFor(renderer);
						var throwDistance : Point = _mouseTracker.getThrowDistance();
	
						target.x += throwDistance.x;
						target.y += throwDistance.y;
					}
				}
			}
			return false;
		}
	}
}